#include <stdio.h>
#include <stdlib.h>
#include "Common.h"

typedef int ElemType;
typedef struct {
    ElemType data[MAXSIZE];
    int front;
    int rear;
} SqQueue;

typedef struct Node {
    ElemType data;
    struct Node *next;
} Node, *QueuePtr;
typedef struct {
    QueuePtr front;
    QueuePtr rear;
    int length;
}LinkQueue;

Status initLinkQueue(LinkQueue *queue);

Status enLinkQueue(LinkQueue *queue, ElemType e);

Status deLinkQueue(LinkQueue *queue, ElemType *e);

Status initQueue(SqQueue *queue);

Status enQueue(SqQueue *queue, ElemType e);

Status deQueue(SqQueue *queue, ElemType *e);

int queueLength(SqQueue *queue);

int main() {
    SqQueue queue;
    initQueue(&queue);
    printf("the queue length=%d\n", queueLength(&queue));
    enQueue(&queue, 99);
    ElemType e;
    deQueue(&queue, &e);
    printf("the element is %d and the queue length=%d\n", e,
           queueLength(&queue));

    LinkQueue linkQueue;
    initLinkQueue(&linkQueue);
    enLinkQueue(&linkQueue, 100);
    ElemType el;
    deLinkQueue(&linkQueue, &el);
    return 0;
}

Status enLinkQueue(LinkQueue *queue, ElemType e) {
    Node *node = (Node *)malloc(sizeof(Node));
    if (!node) {
        return ERROR;
    }
    node->data = e;
    node->next = NULL;
    queue->rear->next = node;
    queue->rear = node;
    queue->length++;
    return OK;
}

Status deLinkQueue(LinkQueue *queue, ElemType *e) {
    if (queue->front == queue->rear) {
        return ERROR;  //队列长度为0的时候
    }
    Node *temp = queue->front->next;
    queue->front->next = temp->next;
    *e = temp->data;
    if (queue->rear == temp) {
        queue->rear = queue->front;
    }
    queue->length--;
    free(temp);
    return OK;
}

Status initLinkQueue(LinkQueue *queue) {
    Node *head = (Node *)malloc(sizeof(Node));
    if (!head) {
        return ERROR;
    }
    head->next = NULL;
    queue->front = head;
    queue->rear = head;
    queue->length = 0;
    return OK;
}

Status deQueue(SqQueue *queue, ElemType *e) {
    //队列是空的
    if (queueLength(queue) == 0) {
        return ERROR;
    }
    *e = queue->data[queue->front++];
    return OK;
}

int queueLength(SqQueue *queue) {
    return (queue->rear - queue->front + MAXSIZE) % MAXSIZE;
}

Status enQueue(SqQueue *queue, ElemType e) {
    //判断队列是否满了
    int rear = queue->rear;
    int front = queue->front;
    int queueSize = MAXSIZE - 1;
    if ((rear + 1) % MAXSIZE == front) {
        return ERROR;
    }
    queue->data[queue->rear++] = e;
    return OK;
}

Status initQueue(SqQueue *queue) {
    queue->front = 0;
    queue->rear = 0;
    return OK;
}